package com.example.userclient.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.walknavi.WalkNavigateHelper
import com.baidu.mapapi.walknavi.adapter.IWEngineInitListener
import com.baidu.mapapi.walknavi.adapter.IWNaviCalcRouteListener
import com.baidu.mapapi.walknavi.adapter.IWRoutePlanListener
import com.baidu.mapapi.walknavi.model.WalkRoutePlanError
import com.baidu.mapapi.walknavi.params.RouteNodeType
import com.baidu.mapapi.walknavi.params.WalkNaviLaunchParam
import com.baidu.mapapi.walknavi.params.WalkRouteNodeInfo
import com.example.userclient.Main.ClientInfoHolder
import com.example.userclient.R
import com.example.userclient.adapter.NavigationAdapter
import com.example.userclient.databinding.NeiborLocalclientBinding
import com.example.userclient.design.Observer
import com.example.userclient.design.Subject


class NavigationActivity : AppCompatActivity() ,Observer{

    private var mapView:MapView? = null
    private var mmap:BaiduMap? = null
    private var ibind:NeiborLocalclientBinding ?=null
    private var nothingView:TextView?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bind = DataBindingUtil.setContentView<NeiborLocalclientBinding>(
                this,
                R.layout.neibor_localclient
        )

        mapView = bind.neiborBmapView
        ibind = bind
//        bind.locDescribe = ClientInfoHolder.locationDescribe
        nothingView = bind.nothingText
        if (ClientInfoHolder.clientMapWithin1000?.size == 0){
//            bind.nothingText.visibility = View.VISIBLE
            bind.isShow = true
            NavigationAdapter.dataSet = ArrayList()
        }else{
            bind.isShow = false
            NavigationAdapter.dataSet = ClientInfoHolder.clientMapWithin1000
        }

        bind.neighborList.adapter =NavigationAdapter

        bind.neighborList.layoutManager = LinearLayoutManager(this)

        mmap = mapView!!.map

        Log.i("NavigationActivity", "Created!!")

        init()

        NavigationAdapter.setOnItemClickListener(object : NavigationAdapter.OnItemClickListener {
            override fun onItemClick(itemView: View?, position: Int) {

                Log.i("baidu", "click")

                val heartBeatInfo = NavigationAdapter.dataSet?.elementAt(position)

                Log.i("baidu", heartBeatInfo!!.position.address)
                WalkNavigateHelper.getInstance().initNaviEngine(this@NavigationActivity, object : IWEngineInitListener {
                    override fun engineInitSuccess() {
                        //引擎初始化成功的回调

                        Log.i("baidu", "engineInitSuccess")
                        heartBeatInfo?.position?.let {
                            ClientInfoHolder.position?.let { it2 ->

                                Log.i("baidu", "engineInitSuccess2")
                                Log.i("baidu", heartBeatInfo!!.position.address)
                                val startPt = LatLng(it2.latitude, it2.longitude)
                                val endPt = LatLng(it.latitude, it.longitude)
                                val start = WalkRouteNodeInfo()
                                val end = WalkRouteNodeInfo()

                                start.location = startPt
                                start.type = RouteNodeType.KEYWORD;
                                start.setKeyword("起点 ");
                                end.location = endPt
                                end.type = RouteNodeType.KEYWORD;
                                end.setKeyword("终点 ");
                                val mParam = WalkNaviLaunchParam().startNodeInfo(start).endNodeInfo(end)



                                WalkNavigateHelper.getInstance().routePlanWithRouteNode(mParam, object : IWRoutePlanListener {
                                    override fun onRoutePlanStart() {
                                        //开始算路的回调

                                        Log.i("baidu", "onRoutePlanStart")
                                    }

                                    override fun onRoutePlanSuccess() {
                                        //算路成功
                                        //跳转至诱导页面

//                                        Log.i("baidu","onRoutePlanSuccess")
//                                        val intent = Intent(this@NavigationActivity, GotoActivity::class.java)
//                                        startActivity(intent)
                                        naviCalcRoute(0);
                                    }

                                    override fun onRoutePlanFail(walkRoutePlanError: WalkRoutePlanError) {
                                        //算路失败的回调
                                        Log.i("baidu", "onRoutePlanFail")
                                    }
                                })
                                return
                            }
                        }

                        Toast.makeText(this@NavigationActivity, "网络请求出错", Toast.LENGTH_SHORT).show()


                    }

                    override fun engineInitFail() {
                        //引擎初始化失败的回调

                        Log.i("baidu", "engineInitFail")

                    }
                })


            }
        })

        ClientInfoHolder.attach(this)

    }

    //导航引擎算路
    private fun naviCalcRoute(routeIndex: Int) {
        WalkNavigateHelper.getInstance().naviCalcRoute(routeIndex, object : IWNaviCalcRouteListener {
            override fun onNaviCalcRouteSuccess() {
                Log.d("baidu", "onNaviCalcRouteSuccess")
                val intent = Intent()
                intent.setClass(this@NavigationActivity, GotoActivity::class.java)
                startActivity(intent)
            }

            override fun onNaviCalcRouteFail(error: WalkRoutePlanError) {
                Log.d("baidu", "WalkNavi naviCalcRoute fail")
            }
        })
    }


    override fun update(subject: Subject, vararg args: Any) {
        val target = subject as ClientInfoHolder
        val isShow = target.clientMapWithin1000?.size==0
        reDrawTextView(isShow)
    }

    private fun reDrawTextView(isShow: Boolean){
        nothingView?.let {
            if (isShow){
                it.visibility = View.VISIBLE
            }else{
                it.visibility = View.GONE
            }
        }
    }

    private fun  init (){


        mapView!!.map.mapType = BaiduMap.MAP_TYPE_NORMAL
        mapView!!.map.isMyLocationEnabled = true

        val update = MapStatusUpdateFactory.newLatLng(ClientInfoHolder.ll)
        mapView!!.map.animateMapStatus(update)


        val builder: MapStatus.Builder = MapStatus.Builder()
        builder.zoom(18.0f)
        mapView!!.map.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))



        mapView!!.map.setMyLocationData(ClientInfoHolder.myloc)

        ClientInfoHolder.clientMapWithin1000?.let {
            val bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.local_client)


            for (i in it){
                Log.i("Navigation", "Alive neighborClient ${i.id}")
                val point = LatLng(i.position.latitude, i.position.longitude)

                val option: OverlayOptions = MarkerOptions()
                        .position(point)
                        .icon(bitmap)

                mapView!!.map.addOverlay(option);
            }
        }



        mapView!!.map.setOnMarkerClickListener {
            Log.i("NavigationView", "$it")
             false
        }

//        val targetBitMap = BitmapDescriptorFactory
//                .fromResource(R.drawable.target_client)
//
//        book?.position?.let {
//            val point = LatLng(it.latitude, it.longitude)
//            val option: OverlayOptions = MarkerOptions()
//                    .position(point)
//                    .icon(targetBitMap)
//
//            mapView!!.map.addOverlay(option);
//        }
    }


    override fun onDestroy() {
        ClientInfoHolder.detach(this)
        super.onDestroy()
    }

    companion object{
        fun actionStart(context: Context){
            val intent = Intent(context, NavigationActivity::class.java)
            context.startActivity(intent)
        }
    }
}